//
//  GoodsListCell.swift
//  smosky
//
//  Created by zhuxietong on 2018/6/7.
//  Copyright © 2018年 tianrun. All rights reserved.
//

import Foundation
import AsyncDisplayKit
import soapp
import Eelay


extension Goods{
    
    public class Filter {
        public var cate:[String:Any]? = nil
        public var order:[String:Any]? = nil
        public var price:[String:Any]? = nil
        public var hot:[String:Any]? = nil
        public var searchKey:String? = nil
        public var updateFilter:(_ values:[String:Any])->Void = {_ in}
        
        public init() {
            
        }
        public var params:[String:Any]{
            get{
                var values = [String:Any]()
                if let _cate = cate{
                    values = values + _cate
                }
                if let _order = order{
                    values = values + _order
                }
                if let _searchKey = searchKey{
                    values = values + ["keyword":_searchKey]
                }
                return values
            }
        }
    }

    
    public enum Tags:String{
        
        case tag1 = "自营"
        case tag2 = "热门单品"
        case tag3 = "包邮"
        case tag4 = "正品"
        
        static func some()->[[String:String]]
        {
            let info:[[String:String]] = [
                ["name":"自营","hex":"#3C4AD799"],
                ["name":"热门单品","hex":"#F190A9"],
                ["name":"包邮","hex":"#BCBCBC"],
                ["name":"正品","hex":"#BCBCBC"],
            ]
            return SandBox.random(count: 3, source: info)
        }
    }
    
    public enum ActiveType{
        case paimai
        case duobao
        case tuangou
        case prebuy
        case none
        
        @discardableResult
        public static func markCellID(item:NSMutableDictionary){
            let t = ActiveType(item: item)
            switch t {
            case .prebuy:
                item["cellID"] = "pre"
            default:
                break
            }
          
        
        }
        public init(item:NSMutableDictionary) {
            if(item["presell.ispresell",""] == "1"){
                self = .prebuy
                return
            }
            self = .none
        }
        
    }

    
    
    public enum PaiMaiProcess{
        case prepare(tag:String)
        case willStart(tag:String)//剩余时间
        case begined(tag:String)
        case finished(tag:String)
        case invalid
        
        public static func create(begin:Date,end:Date)->PaiMaiProcess{
            
            var process:PaiMaiProcess = .invalid            
            let beginInfo = begin.timeSince()
            if beginInfo.0 == .later
            {
                if begin["YYYYMMdd"] == Date()["YYYYMMdd"]
                {
                    process = PaiMaiProcess.willStart(tag: beginInfo.1)
                }
                else{
                    process = PaiMaiProcess.prepare(tag: begin["yyyy年MM月dd日 MM:hh"])
                }
            }
            else
            {
                let endInfo = end.timeSince()
                if endInfo.0 == .later
                {
                    process = PaiMaiProcess.begined(tag: endInfo.1)
                }
                else
                {
                    process = PaiMaiProcess.finished(tag: end["yyyy年MM月dd日 MM:hh"])
                }
            }
            return process
            
        }
        
        
        public var name:(name:String,color:UIColor)
        {
            get{
                switch self {
                case .prepare(_):
                    return ("拍卖".loc,___shop.tint)
                case .willStart(_):
                    return ("即将开拍".loc,___shop.tint)
                case .begined(_):
                    return ("拍卖中".loc,___shop.tint)
                case .finished(_):
                    return ("拍卖结束".loc,._disable)
                default:
                    return ("已失效".loc,._disable)
                }
            }
        }
    }
    
}






public func timeStringTotimeStamp1(_ stringTime:String)->String {
    
    let dfmatter = DateFormatter()
    dfmatter.dateFormat="yyyy-MM-dd HH:mm"
    let date = dfmatter.date(from: stringTime)
    
    let dateStamp:TimeInterval = date!.timeIntervalSince1970
    
    let dateSt:Int64 = Int64(dateStamp)
    return String(dateSt)
}

extension Goods
{
    public static var cellSelector:TP.selector = [
        "<default>":BaseCell.self,
        "cellID<paimai>":PaiMaiCell.self,
        "cellID<group>":GroupListCell.self,
        "cellID<pre>":BaseCell.self
    ]
    
    open class PaiMaiCell: BaseCell {
        public var process:Goods.PaiMaiProcess = .invalid
        {
            didSet{

                if (isInTableVisible && isInControllerVisible)
                {
                    let name = process.name
                    activeBt.setAttributedTitle(name.name.ui.font11.cl_fff.astring, for: .normal)
                    activeBt.contentEdgeInsets = [3,6]
                    activeBt.backgroundColor = name.color
                    processTimeL.contentEdgeInsets = [3,5]
                    processTimeL.view.bsui.set(radius: 3, width: 0, color: nil)
                    
                    processTimeL.backgroundColor = .clear
                    switch process {
                    case .prepare(tag: let tag):
                        processNameL.attributedText = "开拍时间".loc.ui.font11.cl_666.astring
                        processTimeL.setAttributedTitle(tag.ui.font10.cl_888.astring, for: .normal)
//                        self.startTimer(interval: 1)
                        self.stopTimer()

                    case .willStart(tag: let tag):
                        processNameL.attributedText = "开拍倒计时".loc.ui.font11.cl_666.astring
                        processTimeL.backgroundColor = name.color
                        processTimeL.setAttributedTitle(tag.ui.font10.cl_fff.astring, for: .normal)
                        
                        if tag.contains("秒"){
                            self.startTimer(interval: 1)
                        }
                        else{
                            if tag == "1分钟"
                            {
                                self.startTimer(interval: 1)
                            }
                        }

                    case .begined(tag: let tag):
                        processNameL.attributedText = "剩余时间".loc.ui.font11.cl_666.astring
                        processTimeL.setAttributedTitle(tag.ui.font10.color(color: name.color).astring, for: .normal)
                        
                        if tag.contains("秒"){
                            self.startTimer(interval: 1)
                        }
                        else{
                            if tag == "1分钟"
                            {
                                self.startTimer(interval: 1)
                            }
//                            self.startTimer(interval: 1)
                        }

                    case .finished(tag: let tag):
                        processNameL.attributedText = "拍卖结束".loc.ui.font11.cl_666.astring
                        processTimeL.setAttributedTitle(tag.ui.font10.cl_888.astring, for: .normal)
                        self.stopTimer()
                    case .invalid:
                        self.stopTimer()
                    }
                }
            }
        }
        
        public let processNameL = JoTextNode()
        public let processTimeL = ASButtonNode()
        public var timer:SwiftTimer? = nil
        
        open override func didLayoutRules() {
            observerControllerAction()
        }

        override open func mo_model_reload() {
            super.mo_model_reload()
            
            var index:Int = mo.model[int:"__row__",0] + 0
            var tag = ""
            if index > 9 {
                tag = "0"
            }
            if index >= 60
            {
                index = 59
            }
            
            let current = Date()["yyyy-MM-dd HH"]
            
            
            priceL.attributedText = "起拍价   ".ui.font10.color(color: ._tint).astring + "¥ ".ui.font10.cl_444.astring + "1000".ui.bfont17.astring
            mo.model["begin"] = timeStringTotimeStamp1(current+":\(tag)\(index)")
            mo.model["end"] = timeStringTotimeStamp1("2018年6月11日 20:00")

            let beginStamp = mo.model["begin",""]
            let endStamp = mo.model["end",""]
            
            self.begin = stampToTime(beginStamp)
            self.end = stampToTime(endStamp)
            startTimer()
            updateTime()
        }
        
        func startTimer(interval:Int = 60) {
//            self.updateTime()
            weak var wself = self
            timer?.suspend()
            self.timer = SwiftTimer(interval: .seconds(interval), repeats: true, queue: .main, handler: { (timer) in
                wself?.updateTime()
            })
            timer?.start()
        }
        
        
        func stopTimer() {
            timer?.suspend()
        }

        
        @objc open func updateTime() {
            self.process = PaiMaiProcess.create(begin: begin, end: end)
        }

        public var begin:Date = Date()
        public var end:Date = Date()
        
        override open func changeControllerVisible() {
            if isInControllerVisible
            {
                updateTime()
//                startTimer()
            }
            else{
                stopTimer()
            }
        }
        
        override open func changeTableVisible() {

            if isInTableVisible
            {
                updateTime()
//                startTimer()
            }
            else{
                stopTimer()
            }
        }
        
        open override var rightSpec:_Spec{
            get{
                
                let bar:_Spec = .stack(["v|8","\(106)",_grow(1),_shrink(1),&-.stretch,_justfy(.space_between)], childs: [
                    nameL.Spec,
                    .stack(["h",&-.center,_justfy(.space_between)], childs: [
                        priceL.Spec,
                        buyNumL.Spec,

                        ]),
                    .stack(["h|10",&-.center], childs: [processNameL["20",[4,0,0,0]],processTimeL.Spec])
                    ])
                return bar
            }
        }
    }
    
    open class BaseCell: JoCellNode {
        
        public enum Notice:String,NotifyType {
            
            case controllerDisAppear = "controllerDisAppear"
            case controllerWillAppear = "controllerWillAppear"
            
            public var name: Notification.Name{
                return "BaseCell.\(Notice.self)\(self.rawValue)".notice_name
            }
        }
        
        open func observerControllerAction() {
            __notice.remove(Notice.controllerDisAppear,Notice.controllerWillAppear)
            __notice.observer(Notice.controllerDisAppear,Notice.controllerWillAppear) {[weak self] (type, notice) in
                guard let ctr = self?.content_controller, let sender = notice.object as? UIViewController else{return}
                
                if ctr === sender{
                    switch type{
                    case Notice.controllerDisAppear:
                        self?.isInControllerVisible = false
                    case Notice.controllerWillAppear:
                        self?.isInControllerVisible = true
                    default:
                        break
                    }
                }
            }
        }
        
        
   
        public var isInTableVisible:Bool = true{
            didSet{
                changeTableVisible()
            }
        }
        public var isInControllerVisible:Bool = true{
            didSet{
                changeControllerVisible()
            }
        }
        
        
        public func changeTableVisible() {
            
        }
        
        public func changeControllerVisible() {
            
        }
        
        public let imgV = JoImageNode()
        public let nameL = JoTextNode()
        public let activeBt = ASButtonNode()
        public let priceL = JoTextNode()
        public let infoL = JoTextNode()
        
        public let buyNumL = JoTextNode()
        
        public let saveNumL = JoTextNode()
        public let saveEditBt = ASButtonNode()
        public var saveActionBar:_Spec
        {
            get{
                return .stack(["h|6",&-.center,_grow(1),_shrink(1),_justfy(.space_between)], childs: [
                    saveNumL.Spec,
                    saveEditBt.Spec
                    ])
            }
        }
        
        override open func willLayoutRules() {
            activeBt.contentEdgeInsets = [3,5]
            nameL.textNode.maximumNumberOfLines = 2
        }
        
        
      
        
        open var leftSpec:_Spec{
            get{
                let kit_w = 116
                let w = kit_w
                let bar:_Spec = .back([[0,0,0,0]], over: .stack([w,"\(w)","v",&-.flex_start,_justfy(.flex_end)], childs: [
                    activeBt[_shrink(1),[5]]
                    ]), back: imgV.Spec)
                return bar
            }
        }
        
      
        
        
        open var rightSpec:_Spec{
            get{
                
                let tags_list = self.tags.map { (kit) -> _Spec in
                    return kit.Spec
                }
                
                if mo.model["isSaveCell",FK.NO] == FK.YES
                {
                    let bar:_Spec = .stack(["v|6","\(116)",_grow(1),_shrink(1),&-.stretch,_justfy(.space_between)], childs: [
                        nameL.Spec,
                        .stack(["h|6",&-.center,_justfy(.space_between)], childs: [priceL.Spec,buyNumL.Spec]),
                        saveActionBar
                        ])
                    return bar
                }
                let bar:_Spec = .stack(["v|6",.>"\(116)",_grow(1),_shrink(1),&-.stretch,_justfy(.space_between),_nowrap], childs: [
                    nameL.Spec,
                    .stack(["h|6",&-.center,_justfy(.space_between)], childs: [priceL.Spec,buyNumL.Spec]),
                    .stack(["h",&=.space_between], childs: tags_list)
                    ])
                return bar
            }
        }
        
        override open func specGetter() -> _Spec {
            let spec:_Spec = .stack(["h|10",[14],&-.stretch,_justfy(.space_between),_nowrap], childs: [
                leftSpec,
                rightSpec
                ])
            return spec
        }
        
        
        class GoodsTagNode: MoDisplayNode {
            let bt = ASButtonNode()
            override func specGetter() -> _Spec {
                return _Spec.stack([[2,3]], childs: [
                    bt.Spec
                    ])
//                return _Spec.wrapper(bt.Spec)
            }
        }
        var tags:[GoodsTagNode] = [GoodsTagNode]()
        
        override open func mo_model_reload() {
            
            separatorHeight = TP.separatorHeight
            separatorColor = UIColor.table_bg_color
            
            imgV.img_url = mo.model["thumb",""]
            var title = mo.model["description",""]
            if title.len < 1{
                title = mo.model["title",""]
            }
            nameL.attributedText = title.ui.font14.left.color(color: ._foreground).lineSpace(5).astring
            
            let price = mo.model[float:"marketprice",0]
            priceL.attributedText = "¥ \(price.price_display)".ui.font17.left.color(color: ___shop.priceColor).lineSpace(5).astring
            buyNumL.attributedText = "\(mo.model[int:"salesreal",0])人".ui.font12.color(color: ._weak).astring
            
            infoL.attributedText = "¥ 1000".ui.font14.left.color(color: ._foreground).lineSpace(5).astring
            
//            activeBt.setAttributedTitle("秒杀".ui.font11.cl_fff.astring, for: .normal)
//            activeBt.contentEdgeInsets = [3,6]
//            activeBt.backgroundColor = UIColor(shex: "#E42154")
            
            
            
//            let list1 = Goods.Tags.some()
            
            let tags = DataNode.path(node: "labelname", mo.model, value: NSMutableArray())
            let list = NSMutableArray()
            
            tags.list { (tag:String, i) in
                
                if i < 3
                {
                    let obj = NSMutableDictionary()
                    let self_tag = Goods.self_operated_tag + "商城".loc
                    obj["name"] = tag
                    switch tag{
                    case self_tag:
                        obj["color"] = "#3C4AD7"

                    case "官方正品",Goods.self_operated_tag,"包邮","正品保证":
                        obj["color"] = ___shop.tint
                    default:
                        obj["color"] = ___shop.tint
                    }
                    

                    
                    list.add(obj)
                }
            }
            
            list.list {[weak self] (one:NSMutableDictionary, i) in
                let bt = GoodsTagNode()
                
                let color = UIColor(shex: one["hex",""])
//                bt.bt.backgroundColor = UIColor(shex: one["hex",""])
                bt.bt.contentEdgeInsets = [3,5]
                bt.bt.ui.ntitle(title: one["name",""]).font(size: 10).ncolor(color: color).set(radius: 9, width: TP.separatorHeight, color: color)
//                bt.bt.setAttributedTitle(one["name",""].ui.font(font: UIFont.systemFont(ofSize: 9)).cl_fff.astring, for: .normal)
                self?.tags.append(bt)
            }
            
         
        }
        
        deinit {
            
        }
    }

}

